from ninja import Router

from apps.commom.address import AddressSerializer
from apps.user_applets.address.schemas import AddAddressSchema
from apps.schemas import R
from models.models import Address
from utils.auth import AppletAuthBearer
from utils.decorators import handle_exception

address_router = Router(tags=["用户收货地址"], auth=AppletAuthBearer())


@address_router.get("/addresses", summary="获取用户收货地址列表")
@handle_exception("获取用户收货地址列表失败")
def get_user_addresses(request):
    address = Address.objects.filter(user_id=request.user.id)
    return R.ok(data=AddressSerializer(address, many=True).data)


@address_router.post("/address", summary="添加用户收货地址")
@handle_exception("添加用户收货地址失败")
def add_user_address(request, data: AddAddressSchema):
    Address.objects.create(**data.dict(), user_id=request.user.id)
    return R.ok(msg="添加成功")


@address_router.put("/address/{address_id}", summary="修改用户收货地址")
@handle_exception("修改用户收货地址失败")
def update_user_address(request, address_id: int, data: AddAddressSchema):
    Address.objects.filter(id=address_id).update(**data.dict())
    return R.ok(msg="修改成功")


@address_router.delete("/address/{address_id}", summary="删除用户收货地址")
@handle_exception("删除用户收货地址失败")
def delete_user_address(request, address_id: int):
    if not Address.objects.filter(id=address_id).exists():
        return R.fail("收货地址不存在")
    Address.objects.get(id=address_id).delete()
    return R.ok(msg="删除成功")
